package com.example.Arithmetic.Arithmetic;

import com.example.Arithmetic.Arithmetic.Port.Priority;
import com.example.Arithmetic.Arithmetic.Port.Queue;

/**
 * 日期：2023/10/10
 * 时间：10:16
 * 描述：优先级队列,有序数组实现
 */
public class PriorityQueueOrderlyArray<E extends Priority> implements Queue<E> {
    Priority[] array;
    int size;

    public PriorityQueueOrderlyArray(int capacity) {
        array = new Priority[capacity];
        size = 0;
    }

    @Override
    public boolean offer(E value) {
        if (isEmpty()) {
            return false;
        }
        inter(value);
        size++;
        return true;
    }

    //    插入时排序
    private void inter(E value) {
        int i = size - 1;
        while (i >= 0 && array[i].priority() > value.priority()) {
            array[i + 1] = array[i];
            i--;
        }
        array[i + 1] = value;
    }

    @Override
    public E poll() {
        Priority priority = array[size - 1];
        array[--size] = null;      //help GC
        return (E) priority;
    }

    @Override
    public E peek() {
        return (E) array[size];
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public boolean isFull() {
        return size == array.length;
    }
}
